package com.yinhe.module.zxm.controller;

import com.yinhe.common.annotation.Log;
import com.yinhe.common.constant.UserConstants;
import com.yinhe.common.core.controller.BaseController;
import com.yinhe.common.core.domain.AjaxResult;
import com.yinhe.common.core.domain.entity.Baseinfo;
import com.yinhe.common.core.domain.entity.SysDept;
import com.yinhe.common.core.domain.entity.SysMenu;
import com.yinhe.common.core.domain.entity.SysUser;
import com.yinhe.common.core.page.TableDataInfo;
import com.yinhe.common.enums.BusinessType;
import com.yinhe.common.utils.StringUtils;

import com.yinhe.module.zxm.entity.ApplicationCounts;
import com.yinhe.module.zxm.service.ApplicationService;
import com.yinhe.system.domain.SysApplicationCounts;
import com.yinhe.system.domain.YhContract;
import com.yinhe.system.service.ISysDeptService;
import com.yinhe.system.service.ISysUserService;
import liquibase.pro.packaged.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/zxm/application")
public class ZxmApplicationController extends BaseController {
    @Autowired
    private ApplicationService menuService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取菜单列表id
     */
  //  @PreAuthorize("@ss.hasPermi('system:menu:render')")
    @GetMapping("list")
    public AjaxResult list(SysMenu menu) {


//        menuService.selectRole(roleId);


        menu.setParentId(Long.valueOf(1));

        List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());

        return AjaxResult.success(menus);
    }


    /**
     * 根据菜单编号获取详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:menu:render')")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId) {
        List<SysMenu>  menu = menuService.selectMenuById(menuId);

        SysMenu menu1  = menuService.selectMenuByIdA(menuId);

        return AjaxResult.success(menuService.selectMenuById(menuId));

    }

    /**
     *
     */

    @GetMapping(value = "/router/{menuId}")
    public AjaxResult getInfo1(@PathVariable Long menuId) {
        List<SysMenu>  menu = menuService.selectMenuById(menuId);

        SysMenu menu1  = menuService.selectMenuByIdA(menuId);

        return AjaxResult.success(menuService.selectMenuByIdA(menuId));

    }


    /**
     * 查询常规应用
     */


    @GetMapping(value = "/normal")
    public AjaxResult getNormal(){
        long start  =System.currentTimeMillis();
        ArrayList<SysMenu> list = new ArrayList<>();
        ArrayList<SysMenu> list1 = new ArrayList<>();
        List<SysMenu> normalmenu  = menuService.getNormalList();


        for (SysMenu b:normalmenu){
            //System.out.println(b+"70");
            if(b.getMenuType().equals("C")){
                list1.add(b);
            }
           // System.out.println(list1);
        }

        for (SysMenu a:list1) {
        Long ParentId =   a.getParentId();
        //根据ParentId查询他的父id
        SysMenu result =   menuService.selectByMenuId(ParentId);
        //获取父路径
        String path1  = result.getPath();
        //父路径+子路径
        a.setPath(path1+"/"+a.getPath());
        //添加中list中
        list.add(a);
            long end  =System.currentTimeMillis();
           // System.out.println("耗时："+(end-start));
        }
        return AjaxResult.success(list);
    }

    //通讯录
    @PreAuthorize("@ss.hasPermi('module:zxm:community')")
    @RequestMapping("/communication")
    public TableDataInfo list(SysUser sysUser,String deptName){
       startPage();
        ArrayList<Object> list = new ArrayList<>();
        //如果传进来的姓名是空的，就直接查询
        if (deptName==null||deptName.length()==0){

           List<SysUser> result  = userService.selectCommunication(sysUser);
            Baseinfo baseinfo = new Baseinfo();
            //这里是做字典判断，如果字典的值是空的，那么for循环遍历赋值，给一个空值
            extracted(result, baseinfo);
            return getDataTable(result);
       }
        if (deptName.length()>0) {
        SysDept dept = deptService.selectByDeptName(deptName);
        if(dept!=null){
            sysUser.setDeptId(dept.getDeptId());
            startPage();
            List<SysUser> result  = userService.selectCommunication(sysUser);
            Baseinfo baseinfo = new Baseinfo();
            //这里是做字典判断，如果字典的值是空的，那么for循环遍历赋值，给一个空值
            extracted(result, baseinfo);
            return getDataTable(result);
        }
        //如果dept是空的，就给一个查询不到的值
        if (dept==null){
            startPage();
            sysUser.setDeptId(11111L);
            List<SysUser> result  = userService.selectCommunication(sysUser);
            Baseinfo baseinfo = new Baseinfo();
            //这里是做字典判断，如果字典的值是空的，那么for循环遍历赋值，给一个空值
            extracted(result, baseinfo);
            return getDataTable(result);
        }

       }

      return getDataTable(list) ;

    }

    public void extracted(List<SysUser> result, Baseinfo baseinfo) {
        for (SysUser user: result){
            //如果Baseinfo()不是空值，并且字典是空的
            if (user.getBaseinfo()!=null){

                if (user.getBaseinfo().getPresentOccupation()==null){
                    baseinfo.setPresentOccupation("");
                    user.setBaseinfo(baseinfo);
                }
                if (user.getBaseinfo().getMilitaryRank()==null){
                    baseinfo.setMilitaryRank("");
                    user.setBaseinfo(baseinfo);
                }

            }
            //如果Baseinfo()是空值，直接赋值
            if (user.getBaseinfo()==null){
                baseinfo.setMilitaryRank("");
                baseinfo.setMilitaryRank("");
                user.setBaseinfo(baseinfo);
            }
        }
    }

    /**
     *
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu) {
        List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
        return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysMenu> menus = menuService.selectMenuList(getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return AjaxResult.error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return AjaxResult.error("菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }


    /**
     *
     * 应用使用日志
     */
    @PreAuthorize("@ss.hasPermi('system:zxm:log')")
    @RequestMapping("/number/{menuId}")
    public AjaxResult getMenu(@PathVariable("menuId") Long menuId) {
        //用户名，用户id,应用id，应用名，次数
        Long userId =  getUserId();
        String username =  getUsername();
        //先根据menuID查找这条应用数据
        SysMenu sysMenu =   menuService.selectMenuByIdA(menuId);
        //查询menuID和menuname
        sysMenu.getMenuId();
        sysMenu.getMenuName();


        return toAjax(menuService.selectFrequency(userId,username,sysMenu.getMenuId(),sysMenu.getMenuName()));
    }


    @RequestMapping("search/number")
    public TableDataInfo list(SysApplicationCounts sysApplicationCounts){
        startPage();
        List<SysApplicationCounts> result = menuService.searchNumber(sysApplicationCounts);

        return getDataTable(result);
    }

}
